import cv2 
import time
import os, sys
import os.path as osp
from datetime import datetime

from matplotlib.ft2font import HORIZONTAL

def save_img_by_rtsp_history(save_dir, cap_ip_info, grab_list):
    start_time, end_time, intervel = grab_list
    cap_ip, channel, user, passwd = cap_ip_info
    # cap_ip = ".".join(cap_ip.split(".")[:-1]) + ".168"

    start = int(time.mktime(time.strptime(start_time, '%Y-%m-%d %H:%M:%S')))
    end = int(time.mktime(time.strptime(end_time, '%Y-%m-%d %H:%M:%S')))

    for ti in range(start, end, intervel):
        save_strip = time.strftime("%Y-%m-%d_%H-%M-%S", time.gmtime(ti + 60*60*8))
        cur_time = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime(ti + 60*60*8))
        rtsp = "rtsp://{}:{}@{}:554/Streaming/tracks/{}01/?starttime={}".format(user, passwd, cap_ip, channel+1, cur_time)
        cap = cv2.VideoCapture(rtsp)
        
        print("ok")
        ret,frame = cap.read()
        print("ret: ", ret, cap_ip)
        if not ret: 
            continue
        cap.release()  

        cur_save_dir = osp.join(save_dir, os.sep.join(datetime.now().strftime("%Y-%m-%d").split("-")), cap_ip, str(channel))
        os.makedirs(cur_save_dir, exist_ok=True)
        height, width = frame.shape[:2]
        
        cv2.imwrite(osp.join(cur_save_dir, "{}.jpg".format(save_strip)), frame)

def save_img_by_rtsp(save_dir, cap_ip_info):
    cap_ip, user, passwd = cap_ip_info
    cap = cv2.VideoCapture("rtsp://{}:{}@{}:554/ch1/sub/av_stream".format(user, passwd, cap_ip))
    #    const std::string videoStreamAddress = "rtsp://admin:swlskjyxgs0617@192.168.31.111:554/h264/ch34/main/av_stream";
    print("ok")
    ret,frame = cap.read()
    print("ret: ", ret, cap_ip)
    if not ret: 
        return ret

    cur_save_dir = osp.join(save_dir, datetime.now().strftime("%Y-%m-%d"), cap_ip)
    os.makedirs(cur_save_dir, exist_ok=True)
    height, width = frame.shape[:2]
    
    ret,frame = cap.read()
    if not ret:
        print("frame is empty")
        return ret
    cv2.imwrite(osp.join(cur_save_dir, "{}.jpg".format(datetime.now().strftime("%Y-%m-%d %H-%M-%S"))), frame)
    cap.release()  
    return True 

def save_video_by_rtsp(save_dir, cap_ip, user, passwd, save_time):
    cap = cv2.VideoCapture("rtsp://{}:{}@{}:554/ch1/sub/av_stream".format(user, passwd, cap_ip))
    #    const std::string videoStreamAddress = "rtsp://admin:swlskjyxgs0617@192.168.31.111:554/h264/ch34/main/av_stream";
    print("ok")
    ret,frame = cap.read()
    print("ret: ", ret)
    if not ret: 
        return ret

    os.makedirs(save_dir, exist_ok=True)
    height, width = frame.shape[:2]
    fourcc = cv2.VideoWriter_fourcc("M","J","P","G")
    name = '{}_{}.avi'.format(cap_ip, datetime.now().strftime("%Y-%m-%d %H-%M-%S"))
    output_movie = cv2.VideoWriter(osp.join(save_dir, name), fourcc, 30, (int(width), int(height)))
    
    start_time = time.time()
    while True:
        ret,frame = cap.read()
        cv2.imshow(cap_ip,frame)
        cv2.waitKey(1)
        output_movie.write(frame)
        # if cv2.waitKey(1) & 0xFF == ord('q'): break

        if time.time() - start_time > save_time: break
           
    cap.release()
    output_movie.release()
    cv2.destroyWindow(cap_ip)

def video_capture():
    # cap = cv2.VideoCapture(0)
    cap = cv2.VideoCapture("rtmp://140.246.93.130:1935/vod/openUrl/mBLVC3C?beginTime=20210605T174929&endTime=20210605T175029&playBackMode=1")
    #    const std::string videoStreamAddress = "rtsp://admin:swlskjyxgs0617@192.168.31.111:554/h264/ch34/main/av_stream";
    print("s")

    ret,frame = cap.read()
    while ret:
        ret,frame = cap.read()
        print(frame.shape)
        # cv2.imshow("frame",frame)
        # if cv2.waitKey(1) & 0xFF == ord('q'):
        #     break
    # cv2.destroyAllWindows()
    cap.release()

def grab_video_by_time(cap_ip, save_dir, per_minute=10):
    # 192.168.100.64 : [True, time]
    his_data = {}

    start = time.time()
    while True:
        cur_time = time.time() 
        time_diff = cur_time - start
        if time_diff < per_minute * 60:
            print(time_diff)
            time.sleep(1)
            continue
        
        for ci in cap_ip:
            if his_data.get(ci[0], None) and \
                his_data[ci[0]][0] == False and \
                cur_time - his_data[ci[0]][1] < 30 * 60:
                continue
            ret = save_img_by_rtsp(save_dir, ci)
            his_data[ci[0]] = [ret, cur_time]

            # save_video_by_rtsp(save_dir, ci, user, passwd, 1*60)
        start = time.time()

if __name__ == "__main__":
    # cap_ip = [
    #     # ["192.168.100.64", "admin", "abcd1234"] ,
    #     # ["192.168.101.64", "admin", "abcd1234"] ,
    #     # ["192.168.102.64", "admin", "abcd1234"] ,
    #     # ["192.168.103.64", "admin", "abcd1234"] ,
    #     # ["192.168.104.64", "admin", "abcd1234"] ,
    #     # ["192.168.105.64", "admin", "abcd1234"] ,
    #     # ["192.168.106.64", "admin", "abcd1234"] ,
    #     # ["192.168.107.64", "admin", "abcd1234"] ,
    #     # ["192.168.108.64", "admin", "abcd1234"] ,
    #     # ["192.168.109.64", "admin", "abcd1234"] ,
    #     # ["192.168.110.64", "admin", "abcd1234"] ,
    #     # ["192.168.111.64", "admin", "abcd1234"] ,
    #     # ["192.168.112.64", "admin", "abcd1234"] ,
    #     # ["192.168.113.64", "admin", "abcd1234"] ,
    #     # ["192.168.114.64", "admin", "abcd1234"] ,
    #     # ["192.168.135.39", "admin", "admin.12345"] ,

    #     ["192.168.201.64", "admin", "abcd1234"] ,
    #     ["192.168.202.64", "admin", "abcd1234"] ,
    #     ["192.168.203.64", "admin", "abcd1234"] ,
    #     ["192.168.204.64", "admin", "abcd1234"] ,

    # ]
    # save_dir = "/home/xc/work/data/car"
    # per_minute = 3
    # grab_video_by_time(cap_ip, save_dir, per_minute)


    # cap_ip = ["192.168.111.64", "admin", "abcd1234"]
    # grab_list = [
    #     ["2021-06-10 10:00:00", "2021-06-10 20:00:00", 10 * 60],
    #     ["2021-06-11 10:00:00", "2021-06-11 20:00:00", 10 * 60],
    #     ["2021-06-25 10:00:00", "2021-06-25 20:00:00", 10 * 60],
    #     ["2021-06-28 06:00:00", "2021-06-28 20:00:00", 10 * 60],
    #     ["2021-06-29 06:00:00", "2021-06-29 20:00:00", 10 * 60],
    #     ["2021-07-01 06:00:00", "2021-07-01 20:00:00", 10 * 60],
    #     ["2021-07-02 06:00:00", "2021-07-02 20:00:00", 10 * 60],
    #     ["2021-07-03 06:00:00", "2021-07-03 20:00:00", 10 * 60],
    #     ["2021-07-04 06:00:00", "2021-07-04 20:00:00", 10 * 60],
    #     ["2021-07-05 06:00:00", "2021-07-06 23:59:00", 10 * 60],
    #     ["2021-07-07 06:00:00", "2021-07-07 20:00:00", 10 * 60],
    # ]
    # for l in grab_list:
    #     save_dir = "/home/xc/work/dataset/pic/leishan"
    #     save_img_by_rtsp_history(save_dir, cap_ip, l[0], l[1], l[2])


    cap_ips = [
        # ["192.10.11.103", 0, "admin", "abcd1234"],
        # ["192.10.11.103", 1, "admin", "abcd1234"],
        # ["192.10.11.106", 0, "admin", "abcd1234"],
        # ["192.10.11.106", 1, "admin", "abcd1234"],
        # ["192.10.11.109", 0, "admin", "abcd1234"],
        # ["192.10.11.109", 1, "admin", "abcd1234"],
        # ["192.10.11.112", 0, "admin", "abcd1234"],
        # ["192.10.11.112", 1, "admin", "abcd1234"],
        # ["192.10.11.115", 0, "admin", "abcd1234"],
        # ["192.10.11.115", 1, "admin", "abcd1234"],
        # ["192.10.11.120", 0, "admin", "abcd1234"],
        # ["192.10.11.120", 1, "admin", "abcd1234"],
        # ["192.10.11.123", 0, "admin", "abcd1234"],
        # ["192.10.11.123", 1, "admin", "abcd1234"],
        # ["192.10.11.126", 0, "admin", "abcd1234"],
        # ["192.10.11.126", 1, "admin", "abcd1234"],
        ["192.10.14.129", 0, "admin", "abcd1234"],
        ["192.10.14.129", 1, "admin", "abcd1234"],
        # ["192.10.14.132", 0, "admin", "abcd1234"],
        # ["192.10.14.132", 1, "admin", "abcd1234"]

    ]
    grab_list = ["2022-08-06 10:00:00", "2022-08-07 20:00:00", 10 * 60]

    for cap_ip in cap_ips:
        save_dir = "/home/xc/work/dataset/pic/leishan"
        save_img_by_rtsp_history(save_dir, cap_ip, grab_list)
